﻿using B.S.BasicData.Api.Write.Application.Command.MyLog;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.Handler.MyLog
{
    public class CreateLogHandler : IRequestHandler<CreateLogCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogModel> logRepo;

        public CreateLogHandler(IBaseRepository<LogModel> logRepo)
        {
            this.logRepo = logRepo;
        }
        public async Task<ApiResult<int>> Handle(CreateLogCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>(); //实例化响应包装类

            //构建日志实体
            var logModel = new LogModel()
            {
                Id = YitIdHelper.NextId(),
                LogDes = request.LogDes,
                Creator = request.Creator,
                CreateTime = DateTime.Now
            };

            var r =await logRepo.CreateAsync(logModel);

            if (r > 0)
            {
                res.Msg = "添加日志成功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else {
                res.Msg = "添加日志失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }

            return res;
        }
    }
}
